package com.example.schoolblog.blog.Provider;


import com.alibaba.fastjson.JSON;
import com.example.schoolblog.blog.Dto.AccessTokenDto;
import com.example.schoolblog.blog.Dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Component
@Slf4j
public class GiteeProvider {
    /** 通过okhttp向gitee认证服务器发送code以获取返回的AccessToken
     *
     * @param accessTokenDTO 传入的待获取认证DTO，包含应用id、密钥、重定向地址等
     * @return AccessToken
     */
    public String getAccessToken(AccessTokenDto accessTokenDTO){
        //设置编码
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        //将要传过去的数据转换成json数据封装进requestbody中
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code&" +
                        "code=" + accessTokenDTO.getCode() + "&" +
                        "client_id=" + accessTokenDTO.getClientId() + "&" +
                        "redirect_uri=" + accessTokenDTO.getRedirectUri() + "&" +
                        "client_secret=" + accessTokenDTO.getClientSecret())
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            //获取返回字符串中的access_token
            String accessToken = string.split("\"")[3];
            return accessToken;
        } catch (IOException e) {
            log.error("getAccessToken error,{}", accessTokenDTO, e);
        }
        return null;
    }

    /** 应用通过 access_token 访问 Open API 使用用户数据。
     *
     * @param accessToken 传入的accessToken用于向Gitee服务器请求用户数据
     * @return
     */
    public UserDto getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            //将String的json对象自动的解析成GiteeUser类的对象
            UserDto userDto = JSON.parseObject(string, UserDto.class);
            return userDto;
        } catch (IOException e) {
            log.error("getUser error,{}", accessToken, e);
        }
        return  null;
    }

}
